<template>
  <div class="state-ment-main guanwang-bg all-baobiao" style="min-height: calc(100vh - 124px);border-radius: 10px">
    <div :style="{paddingTop:100 * (10 / screensStore.bodyHeight) + 'vh',
    paddingLeft:100 * (10 / screensStore.bodyWidth) + 'vw',paddingRight:100 * (10 / screensStore.bodyWidth) + 'vw',
    marginBottom:100 * (10 / screensStore.bodyHeight) + 'vh'}"
         v-if="isEmpty">
      <div class="title-desp">{{ screensStore.selPeriodObj.periodName }}</div>
      <div style="width: 100%;margin:20px 0">
        <div style="margin:20px 0 10px 0">
          <el-form :inline="true" :model="searchData" class="demo-form-inline" style="width: 100%">
            <el-form-item>
              <el-tag
                type="primary"
                effect="dark"
                round
              >
                本期得分率
              </el-tag>
            </el-form-item>
            <el-form-item label="切换区域">
              <el-cascader
                :options="daQuyuList"
                placeholder="请选择区域" clearable
                v-model="levelId"
                @change="changeDefen"
                :props="{ multiple: true, checkStrictly: true,value:'tree',label:'outletsName',emitPath:false}"
              ></el-cascader>
            </el-form-item>
            <el-form-item label="选择分组">
              <el-select v-model="defenGroup" placeholder="请选择所需展示的分组" clearable filterable
                         multiple @change="() => {getDefen()}">
                <el-option v-for="item in defenGroupList" :key="item" :label="item" :value="item"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item>
              <div class="fixed-row">
                <div>
                  <el-button type="primary" link @click="downloadPDF">导出PDF</el-button>
                </div>
                <div>
<!--                  <el-button type="primary" link @click="downloadDOCX">导出DOCX</el-button>-->
                </div>
              </div>
            </el-form-item>
          </el-form>
          <!--          <el-button type="success" @click="exportDeSource">导出得分数据</el-button>-->
        </div>
        <el-card style="width: 100%;margin-bottom: 20px">
          <div style="width: 100%;height: 300px;margin-bottom: 10px" class="mendianshuliangEcharts"></div>
          <div style="width: 100%">
            <el-table :data="deFenTableData" border style="width: 100%"
                      :header-cell-style="{ background: 'rgb(236,158,15)',color:'#fff'}">
              <el-table-column prop="fengongsi" label="区域" align="center" :width="deFenTableData.length ? 120 : 'auto'"></el-table-column>
              <!-- 动态列（各期失分比例） -->
              <el-table-column
                v-for="(column, key) in deFenTableData[0]?.wentizu"
                :key="key"
                :label="key"
                align="center"
                min-width="120px"
              >
                <template #default="scope">
                  {{(scope.row.wentizu[key] || 0)}}
                </template>
              </el-table-column>
              <el-table-column label="总分" prop="total" align="center"
                               :width="deFenTableData.length ? 120 : 'auto'"></el-table-column>
              <el-table-column type="index" :width="deFenTableData.length ? 80 : 'auto'" label="排名" align="center">
                <template #default="scope">
                  <span>{{ getIndex(scope.$index) }}</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>

<!--        历史得分率-->
        <div style="margin:20px 0 10px 0">
          <el-form :inline="true" :model="searchData" class="demo-form-inline" style="width: 100%">
            <el-form-item>
              <el-tag
                type="primary"
                effect="dark"
                round
              >
                历史得分率
              </el-tag>
            </el-form-item>
            <el-form-item label="切换区域">
              <el-cascader
                :options="daQuyuList"
                placeholder="请选择区域" clearable
                v-model="levelId1"
                @change="change1"
                :props="{ multiple: true, checkStrictly: true,value:'tree',label:'outletsName',emitPath:false}"
              ></el-cascader>
            </el-form-item>
            <el-form-item label="选择分组">
              <el-select v-model="defenGroup" placeholder="请选择所需展示的分组" clearable filterable
                         multiple @change="getDefen1">
                <el-option v-for="item in defenGroupList1" :key="item" :label="item" :value="item"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <!--          <el-button type="success" @click="exportDeSource">导出得分数据</el-button>-->
        </div>

        <el-card style="width: 100%;margin-bottom: 20px">
          <div style="width: 100%;height: 300px;" class="mendianshuliangEcharts1"></div>
        </el-card>

        <!-- 本期失分率-->
        <div style="margin:20px 0 10px 0">
          <el-form :inline="true" :model="searchData" class="demo-form-inline" style="width: 100%">
            <el-form-item>
              <el-tag
                type="primary"
                effect="dark"
                round
              >
                本期失分率
              </el-tag>
            </el-form-item>
            <el-form-item label="切换区域">
              <el-cascader
                :options="daQuyuList"
                placeholder="请选择区域" clearable
                v-model="levelId2"
                @change="getDangShifenlist"
                :props="{ multiple: true, checkStrictly: true,value:'tree',label:'outletsName',emitPath:false}"
              ></el-cascader>
            </el-form-item>
          </el-form>
        </div>
        <el-card style="width: 100%;">
          <div style="width: 100%">
            <el-table :data="benqiShifen" border style="width: 100%"
                      :header-cell-style="{ background: 'rgb(236,158,15)',color:'#fff'}">
              <el-table-column prop="kaohexiang1" label="考核项" align="center"
              fixed="left" :width="benqiShifen.length ? 250 : 'auto'"></el-table-column>
              <el-table-column prop="kaohexiang2" label="考核项" align="center"
                               :width="benqiShifen.length ? 250 : 'auto'" fixed="left"></el-table-column>
              <el-table-column prop="kaohedianshu" label="考核店数" align="center" :width="benqiShifen.length ? 120 : 'auto'"
                               fixed="left"></el-table-column>
              <el-table-column prop="shifendianshu" label="失分店数" align="center" :width="benqiShifen.length ? 120 : 'auto'"
                               fixed="left"></el-table-column>
              <!-- 动态列（各期失分比例） -->
              <el-table-column
                v-for="(column, key) in benqiShifen[0]?.geqishifenbilie"
                :key="key"
                :label="key"
                min-width="250px"
              >
                <template #default="scope">
                  <div style="width: 100%;display: flex;justify-content: flex-start;align-items: center">
                    <div style="height: 20px;background: #0bea16" :style="{width:scope.row.geqishifenbilie[key] + '%'}"></div>
                    <div style="margin-left: 5px">
                      {{(scope.row.geqishifenbilie[key] || 0) + '%'}}
                    </div>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>

        <!-- 历史失分率-->
        <div style="margin:20px 0 10px 0">
          <el-form :inline="true" :model="searchData" class="demo-form-inline" style="width: 100%">
            <el-form-item>
              <el-tag
                type="primary"
                effect="dark"
                round
              >
                历史失分率
              </el-tag>
            </el-form-item>
            <el-form-item label="切换区域">
              <el-cascader
                :options="daQuyuList"
                placeholder="请选择区域" clearable
                v-model="levelId4"
                @change="getLiShifenList"
                :props="{ multiple: true, checkStrictly: true,value:'tree',label:'outletsName',emitPath:false}"
              ></el-cascader>
            </el-form-item>
          </el-form>
        </div>
        <el-card style="width: 100%;">
          <div style="width: 100%">
            <el-table :data="lishiShiFen" border style="width: 100%"
                      :header-cell-style="{ background: 'rgb(236,158,15)',color:'#fff'}">
              <el-table-column prop="kaohexiang1" label="考核项" align="center"  fixed="left"
                               :width="lishiShiFen.length ? 250 : 'auto'"></el-table-column>
              <el-table-column prop="kaohexiang2" label="考核项" align="center"
                               :width="lishiShiFen.length ? 250 : 'auto'" fixed="left"></el-table-column>
              <el-table-column prop="kaohedianshu" label="考核店数" align="center" :width="lishiShiFen.length ? 120 : 'auto'" fixed="left"></el-table-column>
              <el-table-column prop="shifendianshu" label="失分店数" align="center" :width="lishiShiFen.length ? 120 : 'auto'" fixed="left"></el-table-column>
              <!-- 动态列（各期失分比例） -->
              <el-table-column
                v-for="(column, key) in lishiShiFen[0]?.geqishifenbilie"
                :key="key"
                :label="key"
                min-width="250px"
              >
                <template #default="scope">
                  <div style="width: 100%;display: flex;justify-content: flex-start;align-items: center">
                    <div style="height: 20px;background: #0bea16" :style="{width:scope.row.geqishifenbilie[key] + '%'}"></div>
                    <div style="margin-left: 5px">
                      {{(scope.row.geqishifenbilie[key] || 0) + '%'}}
                    </div>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </div>

      <div style="width: 100%;">
        <div style="margin-top: 20px">
          <el-form :inline="true" :model="searchData" class="demo-form-inline" style="width: 100%">
            <el-form-item>
              <el-tag
                type="primary"
                effect="dark"
                round
              >
                整体门店排名
              </el-tag>
            </el-form-item>

            <el-form-item label="切换区域">
              <el-cascader
                :options="daQuyuList"
                placeholder="请选择区域" clearable
                v-model="levelId3"
                @change="change3"
                :props="{ multiple: true, checkStrictly: true,value:'tree',label:'outletsName',emitPath:false}"
              ></el-cascader>
            </el-form-item>
          </el-form>
        </div>

        <div style="margin-top: 20px">
          <el-table :data="tableData" style="width: 100%" border
                    :header-cell-style="{ background: 'rgb(250,250,250)'}">
            <el-table-column type="index" width="80" label="序号" align="center" />
            <el-table-column prop="outletsName" label="被访店名称" align="center"></el-table-column>
            <el-table-column prop="outletsName" label="被访店名称" align="center"></el-table-column>
            <el-table-column prop="provinceName" label="省份" align="center"></el-table-column>
            <el-table-column prop="cityName" label="城市" align="center"></el-table-column>
            <el-table-column prop="areaName" label="区县" align="center"></el-table-column>
            <el-table-column prop="score" label="总分" align="center"></el-table-column>
          </el-table>
        </div>
      </div>

      <div style="height: 100px"></div>
    </div>
    <div v-else style="width: 100%;height: 100%">
      <el-empty description="请先选择期次">
        <el-button type="primary" @click="toIssueselect">选择期次</el-button>
      </el-empty>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import * as echarts from 'echarts'
  import { screenStore } from '~/stores/modules/screen'
  import { onMounted, ref } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import { exportDataInfo } from '~/api/statementview'
  import { getBaoZhengTi, getZongPai, getQuyu, exportWenTi,exportPDF,getDeFenTable,getDangShiFen,lishiShiFenList } from '~/api/public'
  import domtoimage from 'dom-to-image'
  import { isClient } from '@vueuse/core'
  // 动态导入jsPDF，避免SSR问题
  let jsPDF = null
  let Document = null
  let Packer = null
  let Paragraph = null
  let ImageRun = null
  let SectionType = null
  let saveAs = null
  if (isClient) {
    import('file-saver').then(module => {
      saveAs = module.saveAs
    }).catch(err => {
      console.error('Failed to load saveAs:', err)
    })
    import('jspdf').then(module => {
      jsPDF = module.default
    }).catch(err => {
      console.error('Failed to load jsPDF:', err)
    })
    import('docx').then(module => {
      Document = module.Document
      Packer = module.Packer
      Paragraph = module.Paragraph
      ImageRun = module.ImageRun
      SectionType = module.SectionType
    }).catch(err => {
      console.error('Failed to load jsPDF:', err)
    })
  }
  let mendianshuliangEcharts = null
  let mendianshuliangEcharts1 = null
  let echart = echarts
  let periodId = ''
  const screensStore = screenStore()
  const route = useRoute()
  const router = useRouter()
  const isEmpty = ref(false)
  const tableHeader = ref([
    // 第一份问卷header
    [
      {
        title: '积极向上',
        prop: 'reqinghudong'
      },
      {
        title: '活跃展示',
        prop: 'huoyuezhanshi'
      },
      {
        title: '体验刺激',
        prop: 'shichuantiyan'
      },
      {
        title: '爱情体验',
        prop: 'aiqingtiyan'
      }
    ],
    [
      {
        title: '积极向上',
        prop: 'reqinghudong'
      },
      {
        title: '活跃展示',
        prop: 'huoyuezhanshi'
      },
      {
        title: '体验刺激',
        prop: 'shichuantiyan'
      }
    ]
  ])
  const deFenTableData = ref([])
  const levelId = ref([])
  const benqiShifen = ref([])
  const lishiShiFen = ref([])
  const searchData = reactive({
    state: '',
    outletsName: '',
    provinceName: '',
    cityName: '',
    areaName: '',
    addressList: []
  })
  const tableData = ref([])
  const levelId1 = ref([])
  const levelId2 = ref('')
  const levelId3 = ref('')
  const levelId4 = ref('')
  const optionTiaoXing = reactive({
    title: {
      text: '本期得分率',
      textStyle: {
        color: '#000',
        fontSize: 18
      },
      left: 0,
      top: 0
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
        opacity: 0.5
      }
    },
    toolbox: {
      show: true,
      feature: {
        saveAsImage: {}  // 导出图片
        // magicType: { show: true, type: ['line', 'bar'] }
      }
    },
    grid: {
      top: 40,
      left: 40,
      right: 0,
      bottom: 20
    },
    yAxis: {
      type: 'value',
      boundaryGap: [0, 1],
      axisLine: {
        show: true,
        symbol: ['none', 'arrow'],
        lineStyle: {
          color: '#9dc5f1'
        }
      },
      splitLine: {
        show: false,
        interval: 2,
        lineStyle: {
          color: 'rgb(14, 174, 246)'
        }
      },
      axisLabel: {
        fontWeight: 550,
        fontFamily: 'Microsoft YaHei',
        color: '#9dc5f1'
      }
    },

    xAxis: {
      type: 'category',
      data: ['MYBODY-A-01期'],
      axisLabel: {
        color: '#9dc5f1',
        fontFamily: 'Microsoft YaHei',
        fontWeight: 800
      },
      axisLine: {
        show: true,
        symbol: ['none', 'arrow'],
        lineStyle: {
          color: '#9dc5f1'
        }
      }
    },
    series: [
      {
        'type': 'bar',
        'data': [
          88
        ],
        'name': '热情互动',
        'barWidth': '5%',
        barGap: '200%',
        'label': {
          'show': true,
          'position': 'top',
          'fontFamily': 'Microsoft YaHei',
          'color': '#efba0c',
          'formatter': '{a} \n {c}',
          textStyle: {
            lineHeight: 20, // 行间距
            align: 'center'
          },
          'fontWeight': 600
        },
        itemStyle: {
          borderRadius: [5, 5, 0, 0]
        }
      },
      {
        'type': 'bar',
        'data': [
          80
        ],
        'name': '服务体验',
        'barWidth': '5%',
        barGap: '200%',
        'label': {
          'show': true,
          'position': 'top',
          'fontFamily': 'Microsoft YaHei',
          'color': '#efba0c',
          'fontWeight': 600,
          'formatter': '{a} \n {c}',
          textStyle: {
            lineHeight: 20, // 行间距
            align: 'center'
          },
        },
        itemStyle: {
          borderRadius: [5, 5, 0, 0]
        }
      },
      {
        'type': 'bar',
        'data': [
          100
        ],
        'name': '服务感受',
        'barWidth': '5%',
        barGap: '200%',
        'label': {
          'show': true,
          'position': 'top',
          'fontFamily': 'Microsoft YaHei',
          'color': '#efba0c',
          'formatter': '{a} \n {c}',
          textStyle: {
            lineHeight: 20, // 行间距
            align: 'center'
          },
          'fontWeight': 600
        },
        itemStyle: {
          borderRadius: [5, 5, 0, 0]
        }
      },
      {
        'type': 'bar',
        'data': [
          100
        ],
        'name': '服务评价',
        'barWidth': '5%',
        barGap: '200%',
        'label': {
          'show': true,
          'position': 'top',
          'fontFamily': 'Microsoft YaHei',
          'color': '#efba0c',
          'formatter': '{a} \n {c}',
          textStyle: {
            lineHeight: 20, // 行间距
            align: 'center'
          },
          'fontWeight': 600
        },
        itemStyle: {
          borderRadius: [5, 5, 0, 0]
        }
      },
      {
        'type': 'bar',
        'data': [
          80
        ],
        'name': '专业知识',
        'barWidth': '5%',
        barGap: '200%',
        'label': {
          'show': true,
          'position': 'top',

          'fontFamily': 'Microsoft YaHei',
          'color': '#efba0c',
          'formatter': '{a} \n {c}',
          textStyle: {
            lineHeight: 20, // 行间距
            align: 'center'
          },
          'fontWeight': 600
        },
        itemStyle: {
          borderRadius: [5, 5, 0, 0]
        }
      },
      {
        'type': 'bar',
        'data': [
          100
        ],
        'name': '品牌形象',
        'barWidth': '5%',
        barGap: '200%',
        'label': {
          'show': true,
          'position': 'top',
          'fontFamily': 'Microsoft YaHei',
          'color': '#efba0c',
          'formatter': '{a} \n {c}',
          textStyle: {
            lineHeight: 20, // 行间距
            align: 'center'
          },
          'fontWeight': 600
        },
        itemStyle: {
          borderRadius: [5, 5, 0, 0]
        }
      }
    ]
  })
  const optionTiaoXing1 = reactive({
    title: {
      text: '历史得分率',
      textStyle: {
        color: '#000',
        fontSize: 18
      },
      left: 0,
      top: 0
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
        opacity: 0.5
      }
    },
    toolbox: {
      show: true,
      feature: {
        saveAsImage: {},  // 导出图片
        // magicType: { show: true, type: ['line', 'bar'] }
      }
    },
    grid: {
      top: 40,
      left: 40,
      right: 0,
      bottom: 20
    },
    yAxis: {
      type: 'value',
      boundaryGap: [0, 1],
      axisLine: {
        show: true,
        symbol: ['none', 'arrow'],
        lineStyle: {
          color: '#9dc5f1'
        }
      },
      splitLine: {
        show: false,
        interval: 2,
        lineStyle: {
          color: 'rgb(14, 174, 246)'
        }
      },
      axisLabel: {
        fontWeight: 550,
        fontFamily: 'Microsoft YaHei',
        color: '#9dc5f1'
      }
    },

    xAxis: {
      type: 'category',
      data: [],
      axisLabel: {
        color: '#9dc5f1',
        fontFamily: 'Microsoft YaHei',
        fontWeight: 800
      },
      axisLine: {
        show: true,
        symbol: ['none', 'arrow'],
        lineStyle: {
          color: '#9dc5f1'
        }
      }
    },
    series: []
  })
  const defenGroup = ref([])
  const defenGroupList = ref([])
  const defenGroupList1 = ref([])
  const daQuyuList = ref([])
  const xiaoQuyuList = ref([])
  function changeDefen(){
    getDefen()
    getDefenTableList()
  }
  function change1() {
    getDefen1()
  }

  function change3() {
    getZongList()
  }

  onMounted(() => {
    if (route.query.periodId) {
      isEmpty.value = true
      periodId = route.query.periodId
      defenGroupList.value = []
      defenGroupList1.value = []
      getQuyu({ periodId: periodId, projectId: screensStore.selProjectId }).then(res => {
        if (res.code == 200) {
          daQuyuList.value = res.data
          getZongList()
          getDefen()
          getDefenTableList()
          getDefen1()
          getDangShifenlist()
          getLiShifenList()
          nextTick(() => {
            mendianshuliangEcharts = echarts.init(document.querySelector('.mendianshuliangEcharts'))
            mendianshuliangEcharts1 = echarts.init(document.querySelector('.mendianshuliangEcharts1'))
            mendianshuliangEcharts.setOption(optionTiaoXing, true)
          })
        } else {
          daQuyuList.value = []
          xiaoQuyuList.value = []
        }
      })
    } else {
      isEmpty.value = false
    }
  })
  const getIndex = (index) => {
    if (index != (deFenTableData.value.length - 1)) {
      return index + 1
    } else {
      return '———'
    }
  }
  const downloadDOCX = async () => {
    const imageUrl = await domtoimage.toPng(document.querySelector('.all-baobiao'), {
      height: document.querySelector('.all-baobiao').scrollHeight,
      width: document.querySelector('.all-baobiao')?.scrollWidth,
      bgcolor: '#ffffff', // 可选：背景颜色
      quality: 1.0 // 可选：JPEG 图像质量（0-1）
    })
    const arrImg = [imageUrl]
    const { maxWidth, maxHeight } = await getMaxWidthHeight(arrImg)
    const arrData = []
    // 从top的位置开始加图片
    for (let i = 0; i < arrImg.length; i++) {
      const url = arrImg[i]
      const { width, height } = await getImgWidthHeight(url)
      arrData.push(new Paragraph({
        children: [
          new ImageRun({
            data: url,
            transformation: {
              width: width / 2.5,
              height: height / 2
            }
          })
        ]
      }))
    }
    const doc = new Document({
      sections: [
        {
          // type: SectionType.CONTINUOUS,
          // properties: {
          //   page: {
          //     size: {
          //       // 竖向A4: 210mm x 297mm
          //       width: maxWidth,
          //       height: maxHeight,
          //       unit: "twip" // 明确指定单位为twips
          //     },
          //     margin: {
          //       top: 20,
          //       right: 20,
          //       bottom: 20,
          //       left: 20,
          //       unit: "millimeter"
          //     },
          //     orientation: "portrait" // 竖向
          //   }
          // },
          children: [
            ...arrData
          ]
        }
      ]
    })
    // 生成并下载DOCX文件
    const blob = await Packer.toBlob(doc)
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = '报表查看.docx'
    document.body.appendChild(a)
    a.click()

    // 清理
    setTimeout(() => {
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
    }, 100)
  }
  const downloadPDF = async () => {
    const imageUrl = await domtoimage.toPng(document.querySelector('.all-baobiao'), {
      height: document.querySelector('.all-baobiao').scrollHeight,
      width: document.querySelector('.all-baobiao')?.scrollWidth,
      bgcolor: '#ffffff', // 可选：背景颜色
      quality: 1.0 // 可选：JPEG 图像质量（0-1）
    })
    // 生成pdf
    // 第一个参数：l横向，p纵向
    // 第二个参数：计量单位: cm mm px等
    // 第三个参数：格式: 默认a4
    exportPDF({base64Images:[imageUrl]}).then(res => {
      ElMessage.success('整体报表导出成功')
      saveAs(res, '整体报表')
    })
  }

  function getZongList() {
    const params = {
      periodId: periodId
    }
    params.levelTreeList = []
    if (levelId3.value.length) {
      levelId3.value.forEach(item => {
        params.levelTreeList.push(item)
      })
      params.levelTreeList = params.levelTreeList.join('&')
    } else {
      params.levelTreeList = daQuyuList.value[0].tree
    }
    getZongPai(params).then(res => {
      if (res.code == 200) {
        tableData.value = res.data
      } else {
        ElMessage.error(res.msg || '数据获取失败')
      }
    })
  }

  function getDefen() {
    const params = {
      periodId: periodId,
      group: defenGroup.value.join(','),
    }
    params.levelTreeList = []
    if (levelId.value.length) {
      levelId.value.forEach(item => {
        params.levelTreeList.push(item)
      })
      params.levelTreeList = params.levelTreeList.join('&')
    } else {
      params.levelTreeList = daQuyuList.value[0].tree
    }
    getBaoZhengTi(params).then(res => {
      if (res.code == 200) {
        if(res.data){
          if (res.data.length > 5) {
            optionTiaoXing.dataZoom = [
              {
                type: 'inside',
                xAxisIndex: [0],
                start: 1,
                end: 40
              }
            ]
          }
          optionTiaoXing.xAxis.data = []
          optionTiaoXing.series = []
          for (let val of res.data) {
            if (!defenGroupList.value.length) {
              if (JSON.stringify(val.groupStats) != '{}') {
                // 说明有
                const keys = Object.keys(val.groupStats)
                for (let keyVal of keys) {
                  const ind = defenGroupList.value.findIndex(itemKey => itemKey == keyVal)
                  if (ind == -1) {
                    defenGroupList.value.push(keyVal)
                  }
                }
              }
            }
            optionTiaoXing.xAxis.data.push(val.periodName)
            if (JSON.stringify(val.groupStats) != '{}') {
              // 说明有
              const keys = Object.keys(val.groupStats)
              for (let keyVal of keys) {
                const ind = optionTiaoXing.series.findIndex(item => item.name == keyVal)
                if (ind != -1) {
                  optionTiaoXing.series[ind].data.push(val.groupStats[keyVal])
                } else {
                  optionTiaoXing.series.push({
                    type: 'bar',
                    data: [],
                    name: keyVal,
                    'barWidth': '5%',
                    barGap: '200%',
                    label: {
                      show: true,
                      position: 'top',
                      fontFamily: 'Microsoft YaHei',
                      color: '#efba0c',
                      'formatter': '{a} \n {c}',
                      textStyle: {
                        lineHeight: 20, // 行间距
                        align: 'center'
                      },
                      fontWeight: 600
                    },
                    itemStyle: {
                      borderRadius: [5, 5, 0, 0]
                    }
                  })
                  optionTiaoXing.series[optionTiaoXing.series.length - 1].data.push(val.groupStats[keyVal])
                }
              }
            }
          }
          if(defenGroupList.value.length){
            defenGroupList.value = defenGroupList.value.filter(item => item != '总体')
          }
        }
        else{
          optionTiaoXing.xAxis.data = []
          optionTiaoXing.series = []
        }
        nextTick(() => {
          mendianshuliangEcharts.setOption(optionTiaoXing, true)
        })
      }
    })
  }
  function getDefenTableList(){
    const params = {
      projectId:screensStore.selProjectId,
      periodId:periodId,
      group: defenGroup.value.join(','),
    }
    params.levelTreeList = []
    if (levelId.value.length) {
      levelId.value.forEach(item => {
        params.levelTreeList.push(item)
      })
      params.levelTreeList = params.levelTreeList.join('&')
    } else {
      params.levelTreeList = daQuyuList.value[0].tree
    }
    getDeFenTable(params).then(res => {
      if(res.code == 200){
        deFenTableData.value = res.data
      }
      else{
        deFenTableData.value = []
        ElMessage.error(res.msg || '得分数据查询失败')
      }
    })
  }
  function getDefen1() {
    const params = {
      projectId: screensStore.selProjectId,
      group: defenGroup.value.join(','),
    }
    params.levelTreeList = []
    if (levelId1.value.length) {
      levelId1.value.forEach(item => {
        params.levelTreeList.push(item)
      })
      params.levelTreeList = params.levelTreeList.join('&')
    } else {
      params.levelTreeList = daQuyuList.value[0].tree
    }
    getBaoZhengTi(params).then(res => {
      if (res.code == 200) {
        if(res.data){
          if (res.data.length > 5) {
            optionTiaoXing1.dataZoom = [
              {
                type: 'inside',
                xAxisIndex: [0],
                start: 1,
                end: 40
              }
            ]
          }
          optionTiaoXing1.xAxis.data = []
          optionTiaoXing1.series = []
          for (let val of res.data) {
            if (!defenGroupList1.value.length) {
              if (JSON.stringify(val.groupStats) != '{}') {
                // 说明有
                const keys = Object.keys(val.groupStats)
                for (let keyVal of keys) {
                  const ind = defenGroupList1.value.findIndex(itemKey => itemKey == keyVal)
                  if (ind == -1) {
                    defenGroupList1.value.push(keyVal)
                  }
                }
              }
            }
            optionTiaoXing1.xAxis.data.push(val.periodName)
            if (JSON.stringify(val.groupStats) != '{}') {
              // 说明有
              const keys = Object.keys(val.groupStats)
              for (let keyVal of keys) {
                const ind = optionTiaoXing1.series.findIndex(item => item.name == keyVal)
                if (ind != -1) {
                  optionTiaoXing1.series[ind].data.push(val.groupStats[keyVal])
                } else {
                  optionTiaoXing1.series.push({
                    type: 'bar',
                    data: [],
                    name: keyVal,
                    'barWidth': 25,
                    barGap: '200%',
                    label: {
                      show: true,
                      position: 'top',
                      fontFamily: 'Microsoft YaHei',
                      color: '#efba0c',
                      'formatter': '{a} \n {c}',
                      textStyle: {
                        lineHeight: 20, // 行间距
                        align: 'center'
                      },
                      fontWeight: 600
                    },
                    itemStyle: {
                      borderRadius: [5, 5, 0, 0]
                    }
                  })
                  optionTiaoXing1.series[optionTiaoXing1.series.length - 1].data.push(val.groupStats[keyVal])
                }
              }
            }
          }
          if(defenGroupList1.value.length){
            defenGroupList1.value = defenGroupList1.value.filter(item => item != '总体')
          }
        }
        else{
          optionTiaoXing1.xAxis.data = []
          optionTiaoXing1.series = []
        }

        nextTick(() => {
          mendianshuliangEcharts1.setOption(optionTiaoXing1, true)
        })
      }
    })
  }
  function getDangShifenlist(){
    const params = {
      projectId:screensStore.selProjectId,
      periodId:periodId,
    }
    params.levelTreeList = []
    if (levelId2.value.length) {
      levelId2.value.forEach(item => {
        params.levelTreeList.push(item)
      })
      params.levelTreeList = params.levelTreeList.join('&')
    }
    else{
      params.levelTreeList = daQuyuList.value[0].tree
    }
    // else {
    //   if(screensStore.roles.findIndex(role => role == 'level') != -1){
    //     const zongChild = res.data[0].children
    //     if(zongChild.length){
    //       // 如果是层级负责人就是这样
    //       params.levelTreeList = zongChild.map(itemRow => itemRow.tree).join('&')
    //     }
    //   }
    //   else{
    //     params.levelTreeList = daQuyuList.value[0].tree
    //   }
    // }
    getDangShiFen(params).then(res => {
      if(res.code == 200){
        benqiShifen.value = res.data
      }
      else{
        benqiShifen.value = []
      }
    })
  }

  function getLiShifenList(){
    const params = {
      projectId:screensStore.selProjectId,
    }
    params.levelTreeList = []
    if (levelId4.value.length) {
      levelId4.value.forEach(item => {
        params.levelTreeList.push(item)
      })
      params.levelTreeList = params.levelTreeList.join('&')
    }
    else{
      params.levelTreeList = daQuyuList.value[0].tree
    }
    // else {
    //   if(screensStore.roles.findIndex(role => role == 'level') != -1){
    //     const zongChild = res.data[0].children
    //     if(zongChild.length){
    //       // 如果是层级负责人就是这样
    //       params.levelTreeList = zongChild.map(itemRow => itemRow.tree).join('&')
    //     }
    //   }
    //   else{
    //     params.levelTreeList = daQuyuList.value[0].tree
    //   }
    // }
    lishiShiFenList(params).then(res => {
      if(res.code == 200){
        lishiShiFen.value = res.data
      }
      else{
        lishiShiFen.value = []
      }
    })
  }
  async function getMaxWidthHeight(arr) {
    const widthList = []
    const heightList = []
    let maxHeight = 0
    let maxWidth = 0
    for (let i = 0; i < arr.length; i++) {
      const url = arr[i]
      const { width, height } = await getImgWidthHeight(url)
      widthList.push(width)
      heightList.push(height)
    }
    // 把数组变成升序然后倒过来取第一个就是拿最大宽度
    maxWidth = widthList.sort().reverse()[0]
    maxHeight = heightList.sort().reverse()[0]
    return {
      maxWidth,
      maxHeight
    }
  }

  //获取图片宽高
  function getImgWidthHeight(src) {
    return new Promise((resolve, reject) => {
      const img = new Image()
      // 处理跨域图片问题
      img.crossOrigin = 'anonymous'
      img.src = src
      // 图片是否有缓存 如果有缓存可以直接拿 如果没有缓存 需要从onload拿
      if (img.complete) {
        const { width, height } = img
        resolve({
          width,
          height
        })
      } else {
        img.onload = function() {
          const { width, height } = img
          resolve({
            width,
            height
          })
        }
      }
    })
  }

  // 去往期次选择页面
  function toIssueselect() {
    screensStore.activeHomeNav = '期次选择'
    router.replace({ path: '/issueselect' })
  }

  function exportDeSource() {
    const params = {
      periodId: periodId,
      projectId: screensStore.selProjectId,
      group: defenGroup.value.join(','),
      type: 0
    }
    params.levelTreeList = []
    if (levelId1.value.length) {
      levelId1.value.forEach(item => {
        params.levelTreeList.push(item)
      })
      params.levelTreeList = params.levelTreeList.join('&')
    } else {
      params.levelTreeList = daQuyuList.value[0].tree
    }
    exportWenTi(params).then(res => {
      ElMessage.success('得分信息导出成功')
      saveAs(res, '得分信息')
    })
  }


  function onExportData() {
    exportDataInfo(periodId).then(res => {
      ElMessage.success('报表信息导出成功')
      saveAs(res, '报表信息')
    })
  }
</script>

<style scoped lang="less">
  .title-desp {
    font-size: 18px;
    color: #666;
    font-weight: 700;
  }

  .desp-num {
    font-size: 32px;
    color: #53a4f4;
    margin-bottom: 10px;
  }
</style>
